package com.py.credit.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.py.credit.service.XypjRemoteBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.ResourceTemplateFieldsEnum;
import com.py.credit.service.TemplateService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

@RestController
@RequestMapping(value = "/template")
public class TemplateController {

	private static final int ZERO = 0;

	private static final String ZERO_STR = "0";

	private final static String FRONT_TABLE_ID = "template";

	@Autowired
	private TemplateService templateService;

	@Autowired
	private XypjRemoteBaseService xypjRemoteBaseService;

	/**
	 * 获取初始化列
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getOptionalColums.json")
	public RestServiceResult<List<OptionalColumn>> getOptionalColums() {
		RestServiceResult<List<OptionalColumn>> r = new RestServiceResult<List<OptionalColumn>>();
		try {
			r = new RestServiceResult<List<OptionalColumn>>(ResourceTemplateFieldsEnum.getOptionalColumns());
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常");
		}
		return r;
	}


	@RequestMapping(value = "/getTableList.json")
	public RestServiceResult<List<Map<String, Object>>> getTableList(
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
			HttpServletRequest request) {

		String[] configColumns = (String[]) MapCache.get(1000 + "_" + FRONT_TABLE_ID);
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		String[] additionalColumns = { "id" };
		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? ResourceTemplateFieldsEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
		// condition="[{columnEN:\"batch_id\",value:\"EX-test-1-20180326-1174\",type:\"varchar\",fuzzy:fasle}]";
		RestServiceResult<List<Map<String, Object>>> r = new RestServiceResult<List<Map<String, Object>>>();
		try {
			List<Map<String, Object>> tableList = templateService.getByConditionForPage(showColumns, additionalColumns,
					condition, page);
			r = new RestServiceResult<List<Map<String, Object>>>(page.getTotalCount(), tableList);
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常！");
		}
		return r;
	}

	@RequestMapping(value = "/selectOne.json")
	public RestServiceResult<Map<String, Object>> selectOne(
			@RequestParam(value = "id", defaultValue = "", required = true) String id, HttpServletRequest request) {

		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<Map<String, Object>> result = new RestServiceResult<Map<String, Object>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			Map<String, Object> template = templateService.selectOne(id);
			result.setData(template);
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("系统异常！");
		}
		return result;
	}

	@RequestMapping(value = "/listForSelect.json")
	public RestServiceResult<List<Map<String, Object>>> listForSelect(HttpServletRequest request) {

		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			List<Map<String, Object>> listSelect = templateService.listForSelect();
			result.setData(listSelect);
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("系统异常！");
		}
		return result;
	}

	@RequestMapping(value = "/insert.do")
	public RestServiceResult<Map<String, Object>> insert(
			@RequestParam(value = "name", defaultValue = "", required = true) String name,
			@RequestParam(value = "url", defaultValue = "", required = true) String url,
			@RequestParam(value = "mainType", defaultValue = "", required = true) String mainType,
			HttpServletRequest request) {

		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<Map<String, Object>> result = new RestServiceResult<Map<String, Object>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			templateService.insert(name, mainType, url, String.valueOf(userInfo.getId()));
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("系统异常！");
		}
		return result;
	}

	@RequestMapping(value = "/update.do")
	public RestServiceResult<Map<String, Object>> update(
			@RequestParam(value = "id", defaultValue = "", required = true) String id,
			@RequestParam(value = "name", defaultValue = "", required = true) String name,
			@RequestParam(value = "url", defaultValue = "", required = true) String url,
			@RequestParam(value = "mainType", defaultValue = "", required = true) String mainType,
			HttpServletRequest request) {

		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<Map<String, Object>> result = new RestServiceResult<Map<String, Object>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			templateService.update(name, mainType, url, id);
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("系统异常！");
		}
		return result;
	}

	@RequestMapping(value = "/setStatus.do")
	public RestServiceResult<Map<String, Object>> setStatus(
			@RequestParam(value = "id", defaultValue = "", required = true) String id,
			@RequestParam(value = "status", defaultValue = "", required = true) String status,
			HttpServletRequest request) {

		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<Map<String, Object>> result = new RestServiceResult<Map<String, Object>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			templateService.setStatus(id, status);
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("系统异常！");
		}
		return result;
	}

	@RequestMapping(value = "/del.do")
	public RestServiceResult<Map<String, Object>> dels(
			@RequestParam(value = "ids", defaultValue = "", required = true) String ids, HttpServletRequest request) {

		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<Map<String, Object>> result = new RestServiceResult<Map<String, Object>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			List<String> listIds = JSON.parseObject(ids, new TypeReference<List<String>>() {
			});
			templateService.del(listIds);
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("系统异常！");
		}
		return result;
	}

	@RequestMapping(value = "/export")
	public RestServiceResult<List<Map<String, Object>>> exportData(
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
			HttpServletResponse response, HttpServletRequest request) {
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		page.setLimit(1000);
		String[] configColumns = (String[]) MapCache.get(1000 + "_" + FRONT_TABLE_ID);
		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? ResourceTemplateFieldsEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
		List<Map<String, Object>> tableList = templateService.getByConditionForPage(showColumns, null, condition, page);
		try {
			ExcelUtil.downloadExcel(response, tableList, "共享日志", "共享日志", showColumns,
					ResourceTemplateFieldsEnum.getOptionalColumns());
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("共享日志导出异常，请稍后再试！");
			ExceptionLogger.error("共享日志导出异常！", e.getMessage(), e);
			return result;
		}
	}

	@RequestMapping(value = "/getAdvancedConditionColumns.json")
	public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {
		RestServiceResult<List<OptionalColumn>> r = new RestServiceResult<List<OptionalColumn>>();
		try {
			r = new RestServiceResult<List<OptionalColumn>>(ResourceTemplateFieldsEnum.getAdvancedConditionColumns());
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常");
		}
		return r;

	}

	/**
	 * 手动选择展示列
	 * 
	 * @param columns
	 * @return
	 */
	@RequestMapping(value = "/addShowColunms.json")
	public RestServiceResult<String> addShowColunms(
			@RequestParam(value = "columns", required = true) String[] columns) {
		RestServiceResult<String> r = new RestServiceResult<String>();
		try {
			MapCache.set(1000 + "_" + FRONT_TABLE_ID, columns);
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常");
		}
		return r;
	}

}
